<html>
<head>
    <script>
        var logging = true;

        chrome.self.onConnect.addListener(function(port) {
            port.onMessage.addListener(function(msg) {
                switch(msg.operationId) {
                case 1: // saving property
                    proccessSetItem(port, msg);
                    break;
                case 2: // getting property
                    proccessGetItem(port, msg);
                    break;
                default: return;
                }
            });
        });

        function setItem(key, value) {
            try {
                log("Inside setItem:" + key + ":" + value);
                localStorage.removeItem(key);
                localStorage.setItem(key, value);
            } catch(e) {
                log("Error inside setItem");
                log(e);
            }
            log("Return from setItem" + key + ":" + value);
        }
        function getItem(key) {
            var value;
            log('Get Item:' + key);
            try {
                value = localStorage.getItem(key);
            } catch(e) {
                log("Error inside getItem() for key:" + key);
                log(e);
                value = "null";
            }
            log("Returning value: " + value);
            return value;
        }

        function clearStrg() {
            log('about to clear local storage');
            localStorage.clear();
            log('cleared');
        }

        function log(txt) {
            if (logging) {
                console.log(txt);
            }
        }

        function proccessRequest(msg, port) {
            switch(msg.operationId) {
                case 1: // saving property
                    proccessSetItem(port, msg);
                    break;
                case 2: // getting property
                    proccessGetItem(port, msg);
                    break;
                default: return;
            }
        }

        function proccessGetItem(port, msg) {
            port.postMessage({attrValue: getItem(msg.storageAttr), operationId: msg.operationId})
        }

        function proccessSetItem(port, msg) {
            setItem(msg.attrKey, msg.attrValue);
            port.postMessage({message: 'attribute ' + msg.attrKey + ' with value <' + msg.attrValue + '> saved probably', operationId: msg.operationId});
        }

    </script>
</head>
</html>